import { FC, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import avatar from '../../resource/avatar.png'
import style from './style.less'
import { OpenData } from '@tarojs/components'

const Profile: FC = () => {
  const [token, setToken] = useState(() => Taro.getStorageSync('token'))
  const [auth, setAuth] = useState(() => Taro.getStorageSync('auth'))
  const [vip, setVip] = useState(() => Taro.getStorageSync('vip'))

  const [memberShipEndTime, setValidityTime] = useState('')

  const [count, setCount] = useState(0)
  const [discount, setDiscount] = useState(0)

  // 用于防止重复弹窗
  const flag = useRef(false)

  useDidShow(() => {
    setToken(() => Taro.getStorageSync('token'))
    setAuth(() => Taro.getStorageSync('auth'))
    setVip(() => Taro.getStorageSync('vip'))

    Taro.request({
      url: 'http://139.9.123.88:8080/fta-usercenter/membership/membershipEndTime',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token'),
      }),
      success: (data) => {
        console.log('获取的会员到期时间', data);
        setCount(data.data.data?.freeTime ? data.data.data.freeTime : 0)
        setDiscount(data.data.data?.coupons ? data.data.data.coupons : 0)
        if (data.data.data?.endTime) {
          Taro.setStorageSync('vip', 1)
          setVip(1)
          setValidityTime(data.data.data.endTime)
        }
      },
      fail: () => {
        console.log('查询到期时间失败');
      }
    })
  })

  const login = () => {
    if (flag.current) {
      return
    }
    flag.current = true
    Taro.getUserProfile({
      desc: '用于完善会员资料',
      success: () => {
        flag.current = false
        Taro.login({
          success: (res) => {
            console.log('code为', res.code);
            Taro.showLoading({
              title: '加载中',
            })
            Taro.request({
              url: 'http://139.9.123.88:8080/fta-usercenter/auth/login-driver/applets',
              method: 'POST',
              data: JSON.stringify({ code: res.code }),
              success: (data) => {
                console.log('登录', data);

                Taro.setStorageSync('token', data.data.data.token)
                Taro.setStorageSync('auth', data.data.data.isAuth)
                Taro.setStorageSync('vip', data.data.data.isMembership)
                setToken(data.data.data.token)
                setAuth(data.data.data.isAuth)
                setVip(data.data.data.isMembership)
                setCount(data.data.data.is_valid)
                setDiscount(data.data.data.coupons)
                if (data.data.data.isMembership === 1) {
                  setValidityTime(data.data.data.memberShipEndTime)
                }
                Taro.hideLoading()
              },
              fail: () => {
                Taro.hideLoading()
              }
            })
          }
        })
      },
      fail: () => {
        flag.current = false
      }
    })
  }

  const goWallet = () => {
    if (!token) {
      // 未登录

    } else if (!auth) {
      // 已登录，未认证

    } else {
      // 登录且认证

    }
  }

  const quit = () => {
    Taro.showModal({
      title: '提示',
      content: '退出登录后，下次进入小程序需要重新登录，确认继续吗？',
      success: function (res) {
        if (res.confirm) {
          Taro.clearStorage()
          setToken('')
          setAuth('')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  const isLogin = () => {
    if (token && !auth) {
      return (
        <div className="header">
          <div className="img">
            <OpenData type="userAvatarUrl" />
          </div>
          <div className="login">
            未认证
          </div>
          <div className="auth" onClick={() => { Taro.navigateTo({ url: '/packageA/authentication/index' }) }} >去认证</div>
          <div className="desc">完成实名认证享更多权益</div>
        </div>
      )
    } else if (auth) {
      return (
        <div className="header">
          <div className="img">
            <OpenData type="userAvatarUrl" />
          </div>
          <div className="login">
            <OpenData type="userNickName"></OpenData>
          </div>
          <div className="auth">已认证</div>
          <div className="desc">查看认证信息</div>
        </div>
      )
    } else {
      return (
        <div className="header">
          <img src={avatar} alt="" className="img" />
          <div className="login" onClick={login}>立即登录 {'>'}</div>
          <div className="desc">成为满满运注册司机，抢单更简单</div>
        </div>
      )
    }
  }

  const isVIP = () => {
    // 必须已认证，才显示vip窗口
    if (!auth) {
      return
    }
    if (vip === 0) {
      // 从未开通
      return (
        <div className="vip">
          <div className="vip-title">开通尊享会员</div>
          <div className="vip-desc">开通会员 好礼不停</div>
          <div className="vip-btn" onClick={() => { Taro.navigateTo({ url: '/packageD/member/index?status=0' }) }}>立即开通</div>
        </div>
      )
    }
    if (vip === 1) {
      // 未到期
      return (
        <div>
          <div className="vip">
            <div className="vip-title">尊享会员</div>
            <div className="vip-desc">到期时间：{memberShipEndTime}</div>
            <div className="vip-btn" onClick={() => { Taro.navigateTo({ url: '/packageD/member/index?status=0' }) }}>立即续费</div>
          </div>
          <div className="container">
            <div onClick={() => { Taro.navigateTo({ url: '/packageD/member/index?status=1' }) }}>冷链自由享</div>
            <div onClick={() => { Taro.navigateTo({ url: '/packageD/member/index?status=2' }) }}>保油自由享</div>
          </div>
        </div>
      )
    }
    if (vip === 2) {
      // 已到期
      return (
        <div className="vip">
          <div className="vip-title">开通尊享会员</div>
          <div className="vip-desc">您的会员已到期</div>
          <div className="vip-btn" onClick={() => { Taro.navigateTo({ url: '/packageD/member/index?status=0' }) }}>立即开通</div>
        </div>
      )
    }
  }

  return (
    <div className={style.root}>
      {isLogin()}
      <div className="wallet">
        {isVIP()}
        <div className="wallet-container">
          <div className="wallet-item1">
            我的权益
          </div>
          <div className="wallet-item2" onClick={goWallet}>
            权益详情 {'>'}
          </div>
        </div>
        <div className="amount-container">
          <div className="amount-item">
            <div>{auth ? count + '次' : '****'}</div>
            <div>免技术服务费</div>
          </div>
          <div className="amount-item">
            <div>{auth ? discount + '张' : '****'}</div>
            <div>货运券</div>
          </div>
          <div className="amount-item">
            <div>{auth ? '680分' : '****'}</div>
            <div>积分</div>
          </div>
        </div>
      </div>
      {token && <div className="quit" onClick={quit}>退出登录</div>}
    </div>
  )
}

export default Profile